﻿using AntdUI;
using System.Data;
using Wen.Core.Extensions;
using WenAntdUI.Extensions;
using WenAntdUI.Services;

namespace WenAntdUI.Pages.SysAdmin
{
    [Description("字典管理")]
    public partial class SysDictPage : UserControl
    {
        IFreeSql fsql;
        public SysDictPage(IFreeSql fsql, DictService dict)
        {
            this.fsql = fsql;
            InitializeComponent();
            this.adminTable1.SetColumns<SysDict>();

            string category = "";

            this.adminTable1.QueryData = async e =>
            {
                var (items, count) = fsql.Select<SysDict>().Where(a => a.Category == category).ToPageList(e.PageNumber, e.PageSize);
                e.TotalCount = count;
                return items;
            };

            this.adminTable1.QueryClick += AdminTable1_QueryClick;

            this.menu1.SelectChanged += (s, e) =>
            {
                category = e.Value.Text;
                this.adminTable1.Query();
            };
            //刷新字典
            this.adminTable1.SaveItemDataChanged += (s, e) => dict.Refresh();

            InitTree();
        }

        private void AdminTable1_QueryClick(object? sender, string e)
        {
            InitTree();
        }

        private void InitTree()
        {
            var items = fsql.Select<SysDict>().GroupBy(a => a.Category).ToList(a => a.Key);
            this.menu1.Items.Clear();
            this.menu1.Items.AddRange(items.Select(a => new MenuItem(a)));
        }
    }
}
